package com.kws.common.core.utils;

import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <b>OkHttpUtil</b>
 *
 * @description: OkHttpUtil <br>
 * @date: 2024/11/11 14:41 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */
public class OkHttpUtil {
    /**
     * 发送http请求
     * @param requestUrl
     * @return
     */
    public static Object sendOkHttpClient(String requestUrl, String requestMethod, RequestBody body, Map<String, String> headers){
        if(headers == null){
            headers = new HashMap<>();
        }
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS) // 连接超时时间
                .readTimeout(30, TimeUnit.SECONDS) // 读取超时时间
                .writeTimeout(30, TimeUnit.SECONDS) // 写入超时时间
                .build();
        Request request = new Request.Builder()
                .url(requestUrl)
                .method(requestMethod, body != null ? body : null)
                .headers(Headers.of(headers))
                .build();
        try (Response response = client.newCall(request).execute()) { // 使用 try-with-resources 确保自动关闭响应体
            if (response.isSuccessful()) {
                System.out.println(response.header("X-Bce-Request-Id"));
                return response.body().string();
            } else {
                String errorMessage = response.header("X-Bce-Error-Message");
                String requestId = response.header("X-Bce-Request-Id");
                System.out.println("Request failed: " + response.code() + " - "
                        + response.message() + " - " + errorMessage + " - " + requestId);
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
